const { shopToken, userToken } = require('../models/index')
const managerController = require('./managerController')
const errorHelper = require('../util/errorHelper')

class TokenController {
  constructor() {
    // empty
  }
  async createToken({ type, uuId, identityType, loginToken, loginTime, outdateTime, device, ip }) {
    const tokenRec = {
      identityType,
      token: loginToken,
      loginTime,
      outdateTime,
      device,
      ip
    }
    let newToken = null
    if (type === 'shop') {
      tokenRec.shopId = uuId
      newToken = await shopToken.create(tokenRec)
    } else {
      tokenRec.userId = uuId
      newToken = await userToken.create(tokenRec)
    }
    if (!newToken) {
      throw errorHelper(400, 'account or password error')
    }
    return newToken
  }
  // user shop 通用
  async checkToken(loginToken, tokenType) {
    let tokenResult = ''
    if (tokenType === 'manager') {
      tokenResult = await managerController.find({ token: loginToken })
    } else if (tokenType === 'shop') {
      tokenResult = await shopToken.findAll({ where: { token: loginToken, outdateTime: { $gt: new Date() } } })
    } else if (tokenType === 'user') {
      tokenResult = await userToken.findAll({ where: { token: loginToken, outdateTime: { $gt: new Date() } } })
    }
    if (!tokenResult.length) {
      throw errorHelper(401, 'token outdate')
    }
    return tokenResult[0].userId || tokenResult[0].managerId || tokenResult[0].shopId
  }
}

module.exports = new TokenController()
